<script setup>
import {onMounted, ref, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {getUserInfo} from "../../api/userApi.js";

const router = useRouter()
const route = useRoute()
const isCollapse = ref(false)
const activeMenu = ref('dashboard')

// 监听路由变化，更新激活菜单
watch(() => route.path, (newPath) => {
  const routeName = newPath.split('/').pop()
  activeMenu.value = routeName || 'dashboard'
}, {immediate: true})

const userRef = ref({
  name: ''
})

// 菜单数据 - 使用字符串名称引用全局注册的图标
const menuData = [
  {
    index: 'dashboard',
    title: '仪表盘',
    icon: 'TrendCharts',
    route: '/home/dashboard'
  },
  {
    index: 'admin',
    title: '后台管理',
    icon: 'Management',
    children: [
      {index: 'product-manage', title: '商品管理', icon: 'Goods', route: '/home/product-manage'},
      {index: 'category-manage', title: '分类管理', icon: 'Collection', route: '/home/category-manage'},
      {index: 'supplier-manage', title: '供应商管理', icon: 'User', route: '/home/supplier-manage'},
      {index: 'customer-manage', title: '客户管理', icon: 'UserFilled', route: '/home/customer-manage'}
    ]
  },
  {
    index: 'business',
    title: '店铺经营',
    icon: 'ShoppingBag',
    children: [
      {index: 'purchase', title: '采购', icon: 'ShoppingCartFull', route: '/home/purchase'},
      {index: 'sales', title: '销售', icon: 'Sell', route: '/home/sales'},
      {index: 'inventory-adjust', title: '报损报溢', icon: 'DocumentRemove', route: '/home/inventory-adjust'},
      {index: 'other-cost', title: '其他成本', icon: 'Money', route: '/home/other-cost'},
      {index: 'cost-adjust', title: '成本调整', icon: 'Coin', route: '/home/cost-adjust'}
    ]
  },
  {
    index: 'query',
    title: '明细查询',
    icon: 'DocumentCopy',
    children: [
      {index: 'profit-query', title: '利润查询', icon: 'PieChart', route: '/home/profit-query'},
      {index: 'cost-query', title: '成本查询', icon: 'CreditCard', route: '/home/cost-query'},
      {index: 'gross-profit-query', title: '毛利查询', icon: 'TrendCharts', route: '/home/gross-profit-query'},
      {index: 'inventory-query', title: '库存查询', icon: 'Files', route: '/home/inventory-query'}
    ]
  },
  {
    index: 'system-setting',
    title: '系统设置',
    icon: 'Setting',
    route: '/home/system-setting'
  }
]

// 处理菜单选择
const handleMenuSelect = (index) => {
  const findMenuItem = (items, targetIndex) => {
    for (const item of items) {
      if (item.index === targetIndex && item.route) {
        return item
      }
      if (item.children) {
        const found = findMenuItem(item.children, targetIndex)
        if (found) return found
      }
    }
    return null
  }

  const menuItem = findMenuItem(menuData, index)
  if (menuItem && menuItem.route) {
    activeMenu.value = index
    router.push(menuItem.route)
  }
}

// 切换侧边栏收起状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

onMounted(() => {
  // 获取用户信息，验证登录状态
  getUserInfo().then((res) => {
    userRef.value = res
  })
})
</script>

<template>
  <div class="HomePage">
    <!-- 顶部栏 -->
    <div class="HomePage-Header">
      <div class="HomePage-Header-Left">
        <el-button
            type="primary"
            circle
            size="small"
            @click="toggleCollapse"
            class="HomePage-Header-CollapseBtn">
          <el-icon>
            <Menu/>
          </el-icon>
        </el-button>
        <div class="HomePage-Header-Title">进销存系统</div>
      </div>

      <!-- 用户信息区域 -->
      <div class="HomePage-Header-Right">
        <div class="HomePage-Header-Right-UserInfo">
          <el-icon class="HomePage-Header-Right-UserInfo-Avatar">
            <Avatar/>
          </el-icon>
          <span class="HomePage-Header-Right-UserInfo-Name">{{ userRef.name || '用户' }}</span>
        </div>
      </div>
    </div>

    <!-- 主区域 -->
    <div class="HomePage-Main">
      <!-- 侧边栏 -->
      <div class="HomePage-Main-Sidebar" :class="{ 'is-collapse': isCollapse }">
        <el-scrollbar class="HomePage-Main-Sidebar-Scrollbar">
          <el-menu
              :default-active="activeMenu"
              class="HomePage-Main-Sidebar-Menu"
              :collapse="isCollapse"
              :unique-opened="false"
              @select="handleMenuSelect"
              background-color="#ffffff"
              text-color="#606266"
              active-text-color="#409eff">

            <template v-for="menu in menuData" :key="menu.index">
              <!-- 一级菜单（无子菜单） -->
              <el-menu-item
                  v-if="!menu.children"
                  :index="menu.index"
                  class="HomePage-Main-Sidebar-Menu-Item">
                <el-icon>
                  <component :is="menu.icon"/>
                </el-icon>
                <template #title>{{ menu.title }}</template>
              </el-menu-item>

              <!-- 有子菜单的项目 -->
              <el-sub-menu
                  v-else
                  :index="menu.index"
                  class="HomePage-Main-Sidebar-Menu-SubMenu">
                <template #title>
                  <el-icon>
                    <component :is="menu.icon"/>
                  </el-icon>
                  <span>{{ menu.title }}</span>
                </template>

                <el-menu-item
                    v-for="child in menu.children"
                    :key="child.index"
                    :index="child.index"
                    class="HomePage-Main-Sidebar-Menu-SubItem">
                  <el-icon>
                    <component :is="child.icon"/>
                  </el-icon>
                  <template #title>{{ child.title }}</template>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </el-scrollbar>
      </div>

      <!-- 主显示区域 -->
      <div class="HomePage-Main-Content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.HomePage {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;

  &-Header {
    height: 60px;
    background-color: #409eff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
    z-index: 1000;

    &-Left {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    &-Right {
      display: flex;
      align-items: center;

      &-UserInfo {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #ffffff;

        &-Avatar {
          font-size: 24px;
          color: #ffffff;
        }

        &-Name {
          font-size: 14px;
          color: #ffffff;
        }
      }
    }

    &-CollapseBtn {
      background-color: rgba(255, 255, 255, 0.2) !important;
      border-color: rgba(255, 255, 255, 0.3) !important;
      color: #ffffff !important;

      &:hover {
        background-color: rgba(255, 255, 255, 0.3) !important;
        border-color: rgba(255, 255, 255, 0.4) !important;
      }

      &:focus {
        background-color: rgba(255, 255, 255, 0.3) !important;
        border-color: rgba(255, 255, 255, 0.4) !important;
      }
    }

    &-Title {
      color: #ffffff;
      font-size: 20px;
      font-weight: bold;
    }
  }

  &-Main {
    flex: 1;
    display: flex;
    overflow: hidden;

    &-Sidebar {
      width: 240px;
      background-color: #ffffff;
      border-right: 1px solid #e4e7ed;
      transition: width 0.3s ease;

      &.is-collapse {
        width: 64px;
      }

      &-Scrollbar {
        height: 100%;

        :deep(.el-scrollbar__view) {
          height: 100%;
        }
      }

      &-Menu {
        border: none;
        height: 100%;
        min-height: 100%;

        // 自定义菜单项样式
        :deep(.el-menu-item) {
          height: 48px;
          line-height: 48px;
          margin: 4px 8px;
          border-radius: 4px;

          &:hover {
            background-color: #ecf5ff !important;
            color: #409eff !important;
          }

          &.is-active {
            background-color: #409eff !important;
            color: #ffffff !important;

            .el-icon {
              color: #ffffff !important;
            }
          }
        }

        // 子菜单样式
        :deep(.el-sub-menu) {
          .el-sub-menu__title {
            height: 48px;
            line-height: 48px;
            margin: 4px 8px;
            border-radius: 4px;

            &:hover {
              background-color: #ecf5ff !important;
              color: #409eff !important;
            }
          }

          .el-menu-item {
            height: 44px;
            line-height: 44px;
            margin: 2px 8px 2px 24px;
            padding-left: 24px !important;

            &:hover {
              background-color: #ecf5ff !important;
              color: #409eff !important;
            }

            &.is-active {
              background-color: #409eff !important;
              color: #ffffff !important;

              .el-icon {
                color: #ffffff !important;
              }
            }
          }
        }

        // 折叠状态下的样式
        &.el-menu--collapse {
          .el-menu-item,
          .el-sub-menu > .el-sub-menu__title {
            text-align: center;
            padding: 0 !important;
            margin: 4px 8px;
          }
        }
      }
    }

    &-Content {
      flex: 1;
      padding: 16px;
      overflow-y: auto;
      background-color: #ffffff;
      border-radius: 4px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
    }
  }
}

// 全局样式覆盖（针对Element Plus Menu组件）
:deep(.el-menu) {
  .el-icon {
    width: 20px;
    height: 20px;
  }
}
</style>